package processing.main.clock;

import processing.core.*;

import android.util.Log;
import android.view.MotionEvent;
import android.view.KeyEvent;
import android.graphics.Bitmap;
import java.io.*;
import java.util.*;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import android.text.format.DateUtils;
import android.text.format.Time;

import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

class MyCalendar {
	public String name;
	public String id;

	public MyCalendar(String _name, String _id) {
		name = _name;
		id = _id;
	}

	@Override
	public String toString() {
		return name;
	}
}


public class Clock extends PApplet {
	private int maxTextWidth;
	private final int maxTextHeight = 40;
	private final int minTextHeight = 20;
	PFont f;

	private Spinner m_spinner_calender;
	private Button m_button_add;
	private Button m_button_add2;
	private Button m_button_getEvents;
	private TextView m_text_event;
	
	public void setup() {
		background(255);
		orientation(PORTRAIT);
		maxTextWidth = floor(screenWidth - screenWidth / 5);
		f = createFont("HelveticaLTStd-LightCond.otf", 30);

		/* get calendar list and populate the view */
		getCalendars();
		populateCalendarSpinner();
		populateGetEventsBtn();		
	}
	
	private MyCalendar m_calendars[];
	private String m_selectedCalendarId = "0";

	private void getCalendars() {
		String[] l_projection = new String[] { "_id", "displayName" };
		Uri l_calendars;
		if (Build.VERSION.SDK_INT >= 8) {
			l_calendars = Uri.parse("content://com.android.calendar/calendars");
		} else {
			l_calendars = Uri.parse("content://calendar/calendars");
		}
		Cursor l_managedCursor = this.managedQuery(l_calendars, l_projection,
				null, null, null); // all calendars
		// Cursor l_managedCursor = this.managedQuery(l_calendars, l_projection,
		// "selected=1", null, null); //active calendars
		if (l_managedCursor.moveToFirst()) {
			m_calendars = new MyCalendar[l_managedCursor.getCount()];
			String l_calName;
			String l_calId;
			int l_cnt = 0;
			int l_nameCol = l_managedCursor.getColumnIndex(l_projection[1]);
			int l_idCol = l_managedCursor.getColumnIndex(l_projection[0]);
			do {
				l_calName = l_managedCursor.getString(l_nameCol);
				l_calId = l_managedCursor.getString(l_idCol);
				m_calendars[l_cnt] = new MyCalendar(l_calName, l_calId);
				++l_cnt;
			} while (l_managedCursor.moveToNext());
		}
	}
	
	private static final String DATE_TIME_FORMAT = "yyyy MMM dd, HH:mm:ss";

	public static String getDateTimeStr(int p_delay_min) {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_TIME_FORMAT);
		if (p_delay_min == 0) {
			return sdf.format(cal.getTime());
		} else {
			Date l_time = cal.getTime();
			l_time.setMinutes(l_time.getMinutes() + p_delay_min);
			return sdf.format(l_time);
		}
	}

	public static String getDateTimeStr(String p_time_in_millis) {
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_TIME_FORMAT);
		Date l_time = new Date(Long.parseLong(p_time_in_millis));
		return sdf.format(l_time);
	}

	private void populateCalendarSpinner() {
		/****************
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * The R in findViewById should really be R.id.spinner_calendar
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 */
		m_spinner_calender = (Spinner) this.findViewById(R);
		ArrayAdapter l_arrayAdapter = new ArrayAdapter(
				this.getApplicationContext(),
				android.R.layout.simple_spinner_item, m_calendars);
		l_arrayAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		m_spinner_calender.setAdapter(l_arrayAdapter);
		m_spinner_calender.setSelection(0);
		m_spinner_calender
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					@Override
					public void onItemSelected(AdapterView<?> p_parent,
							View p_view, int p_pos, long p_id) {
						m_selectedCalendarId = m_calendars[(int) p_id].id;
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
					}
				});
	}
	
	private void populateGetEventsBtn() {
		/******************************************************
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * THE R in findViewById should really be R.id.button_get_events
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 */
		m_button_getEvents = (Button) findViewById(R);
		m_button_getEvents.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					getEvents();
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}
	
	private ArrayList<Event> getEvents() throws ParseException {
		Uri l_eventUri;
		if (Build.VERSION.SDK_INT >= 8) {
			l_eventUri = Uri.parse("content://com.android.calendar/events");
		} else {
			l_eventUri = Uri.parse("content://calendar/events");
		}
		String[] l_projection = new String[] { "title", "dtstart", "dtend",
				"eventLocation" };
		Cursor l_managedCursor = this.managedQuery(l_eventUri, l_projection,
				"calendar_id=" + m_selectedCalendarId, null,
				"dtstart ASC, dtend ASC");
		// Cursor l_managedCursor = this.managedQuery(l_eventUri, l_projection,
		// null, null, null);
		ArrayList<Event> events = new ArrayList<Event>();
		if (l_managedCursor.moveToFirst()) {
			int l_cnt = 0;
			String l_title;
			String l_begin;
			String l_end;
			String l_location;
			StringBuilder l_displayText = new StringBuilder();
			int l_colTitle = l_managedCursor.getColumnIndex(l_projection[0]);
			int l_colBegin = l_managedCursor.getColumnIndex(l_projection[1]);
			int l_colEnd = l_managedCursor.getColumnIndex(l_projection[2]);
			int l_colLocation = l_managedCursor.getColumnIndex(l_projection[3]);

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd, HH:mm:ss");
			String currTime = sdf.format(new Date());

			do {
				l_title = l_managedCursor.getString(l_colTitle);
				l_begin = getDateTimeStr(l_managedCursor.getString(l_colBegin));
				l_end = getDateTimeStr(l_managedCursor.getString(l_colEnd));
				l_location = l_managedCursor.getString(l_colLocation);

				Date curr = sdf.parse(currTime);
				Date end = sdf.parse(l_end);
				
				if (curr.before(end)) {
					/*l_displayText.append(l_title + "\n" + l_begin + "\n"
							+ l_end + "\n" + l_location
							+ "\n----------------\n");*/
					Event newEvent = new Event(l_title, l_location, l_begin, l_end);
					events.add(newEvent);
				}
				++l_cnt;
			} while (l_managedCursor.moveToNext()/* && l_cnt < 12*/);
			m_text_event.setText(l_displayText.toString());
		}
		return events;
	}
	
	public void draw() {
		fill(255);
		rect(0, 0, sketchWidth(), sketchHeight());
		ArrayList<Event> events = null;
		try {
			events = getEvents();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		for (int i = 0; i < events.size(); i++) {
			drawRect(events.get(i));
		}
		drawHourInfo();
	}

	public void drawRect(Event currentEvent) {
		fill(currentEvent.getColorRed(), currentEvent.getColorGreen(),
				currentEvent.getColorBlue(), 255);
		rect(0, (float) (1.0 - currentEvent.getTopPosition()) * sketchHeight(),
				screenWidth, (currentEvent.getRectangleHeight())
						* sketchHeight());

		fill(0);
		drawEventInfo(currentEvent);

	}

	public void drawEventInfo(Event currentEvent) {
		String eventName = currentEvent.getEventName();
		String eventLocation = currentEvent.getEventLocation();

		float eventHeight = currentEvent.getRectangleHeight() * sketchHeight();
		float eventTop = (float) (1.0 - currentEvent.getTopPosition())
				* sketchHeight();

		float textHeight;
		if (eventHeight > minTextHeight + 9) {
			// Can show both
			textHeight = (eventHeight - 9) / 2;
			if (textHeight > maxTextHeight)
				textHeight = maxTextHeight;
			textFont(f, textHeight);
			eventName = truncateText(eventName);
			eventLocation = truncateText(eventLocation);
			text(eventName, screenWidth - textWidth(eventName), eventTop
					+ textHeight + 3);
			text(eventLocation, screenWidth - textWidth(eventLocation),
					eventTop + (textHeight * 2) + 6);
		} else if (eventHeight > minTextHeight + 6) {
			textHeight = (eventHeight - 6) / 2;
			textFont(f, textHeight);
			eventName = truncateText(eventName);
			text(eventName, textWidth(eventName), eventTop + textHeight + 3);
		}

	}

	public String truncateText(String text) {
		while (text.length() != 0 && textWidth(text) > maxTextWidth) {
			text = text.substring(0, text.length() - 1);
		}
		return text;
	}

	public void drawHourInfo() {
		textFont(f);
		fill(0);
		stroke(0);
		strokeWeight(5);
		text("Now", 5, 30);
		line(0, 30, screenWidth / 5, 30);
		text("1 Hour", 5, (float) (sketchHeight() * .25 - 5));
		line((float) 0.0, (float) (sketchHeight() * .25),
				(float) screenWidth / 5, (float) (sketchHeight() * .25));
		text("3 Hours", 5, (float) (sketchHeight() * .50 - 5));
		line((float) 0.0, (float) (sketchHeight() * .50),
				(float) screenWidth / 5, (float) (sketchHeight() * .50));
		text("6 Hours", 5, (float) (sketchHeight() * .75 - 5));
		line((float) 0.0, (float) (sketchHeight() * .75),
				(float) screenWidth / 5, (float) (sketchHeight() * .75));
		text("12 Hours", 5, (float) (sketchHeight() * 1.0 - 5));
		line((float) 0.0, (float) (sketchHeight() * 1.0),
				(float) screenWidth / 5, (float) (sketchHeight() * 1.0));
		noStroke();
	}

	void randomColorRed() {
		fill(random(195, 254), random(0, 254), random(0, 50), random(155, 255));
	}

	public int sketchWidth() {
		return screenWidth;
	}

	public int sketchHeight() {
		return screenHeight - 30;
	}
}
